package JSF;

import Entidades.Estado;
import Entidades.MovEncarga;
import Entidades.Trabajador;
import JSF.util.JsfUtil;
import JSF.util.PaginationHelper;
import SessionB.MovEncargaFacade;
import java.io.IOException;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import org.primefaces.context.RequestContext;

@Named("movEncargaController")
@SessionScoped
public class MovEncargaController implements Serializable {

    private String cadena_conexion = "jdbc:mysql://localhost:3306/emilima_tradoc";
    private String password = "carloscd3";
    private static Connection conn = null;
    
    private SelectItem[] manufacturerOptions;
    private Trabajador trabaja;
    private MovEncarga current;
    private MovEncarga movencarga;
    private List<MovEncarga> lista;
    private DataModel items = null;
    @EJB
    private SessionB.MovEncargaFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;

    public MovEncargaController() {
        //    manufacturerOptions = createFilterOptions(trabaja);
    }

    public MovEncarga getSelected() {
        if (current == null) {
            current = new MovEncarga();
            selectedItemIndex = -1;
        }
        return current;
    }

    private MovEncargaFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    //************************************************************************
    public String eliminaEncarga() {
        try {
            System.out.println(" ------ Antes de Eliminar ..");
            ejbFacade.remove(movencarga);
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Eliminación Procesada ..!", "Registro Eliminado Correctamente");
            RequestContext.getCurrentInstance().showMessageInDialog(message);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private SelectItem[] createFilterOptions(String[] data) {
        SelectItem[] options = new SelectItem[data.length + 1];

        options[0] = new SelectItem("", "Select");
        for (int i = 0; i < data.length; i++) {
            options[i + 1] = new SelectItem(data[i], data[i]);
        }

        return options;
    }

    public SelectItem[] getManufacturerOptions() {
        return manufacturerOptions;
    }

    public List<MovEncarga> getLista() {
        lista = new LinkedList<MovEncarga>();
        try {
            lista = ejbFacade.findAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lista;

    }

    public void setLista(List<MovEncarga> lista) {
        this.lista = lista;
    }

    public MovEncarga getMovencarga() {
        return movencarga;
    }

    public void setMovencarga(MovEncarga movencarga) {
        this.movencarga = movencarga;
    }

//************************************************************************    
    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (MovEncarga) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new MovEncarga();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("MovEncargaCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (MovEncarga) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            current = movencarga;
            getFacade().edit(current);
            //       JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EditoOk"));
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Moficiación Procesada ..!", "Registro Modificado Correctamente");
            RequestContext.getCurrentInstance().showMessageInDialog(message);
            System.out.println(" modifico Encarga");
        } catch (Exception e) {
//            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Error en Moficiación ..!", "No se realizo Modificado "+e);
//            RequestContext.getCurrentInstance().showMessageInDialog(message);
            System.out.println(" No modifico Encarga");
            e.printStackTrace();
            //JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("EditoMal"));
        }
        return null;
    }

    public String updateorig() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("MovEncargaUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String grabaEncarga() {
        try {
            movencarga.setIdMovEncar(6); 
            Estado est = new Estado();
            est.setIdEstado("01");
            movencarga.setEstado(est);
            current = movencarga;
            ejbFacade.create(current);
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Registro Procesado ..!", "Se Agrego Registro Correctamente");
            RequestContext.getCurrentInstance().showMessageInDialog(message);
        } catch (Exception e) {
            e.printStackTrace();
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Error en Registro ..!", "No Agrego Registro ");
            RequestContext.getCurrentInstance().showMessageInDialog(message);
        }
        return null;
    }

    public void prepareCreateEncarga() { 
        movencarga = new MovEncarga();
        current = new MovEncarga();
    }
      JasperPrint jasperPrint;
//***************************  Reportes PDF  ***********************************    
     public void initov() throws JRException {
        try {
            System.out.println(" Inicio PDF");
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            String idJef = movencarga.getTrabajador().getIdResponsable().toString();
//                    expedient.getCodExp().toString();
            Map parameters = new HashMap();
            parameters.put("P_Jefe", idJef);
            //    JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(listOfUser);
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/MovEncarga.jasper");
            //   jasperPrint = JasperFillManager.fillReport(reportPath, new HashMap(), beanCollectionDataSource);
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);
        } catch (Exception e) {
        }
    }

    public void PDFov(ActionEvent actionEvent) throws JRException, IOException {
        initov();
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        //     httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");
        String fileNa = "Mov_Encarg";
//            ec.setResponseHeader("Content-Disposition", "inline; filename=\"" + fileNa + "\"");
//        httpServletResponse.addHeader("Content-disposition", "inline");
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\"" + fileNa + "\"");
        //             httpServletResponse.addHeader("Content-disposition : inline" , "filename=\"" + fileNa + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }
    
//******************************************************************************    
    public String destroy() {
        current = (MovEncarga) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("MovEncargaDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public MovEncarga getMovEncarga(java.lang.Integer id) {
        return ejbFacade.find(id);
    }

    @FacesConverter(forClass = MovEncarga.class)
    public static class MovEncargaControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            MovEncargaController controller = (MovEncargaController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "movEncargaController");
            return controller.getMovEncarga(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof MovEncarga) {
                MovEncarga o = (MovEncarga) object;
                return getStringKey(o.getIdMovEncar());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + MovEncarga.class.getName());
            }
        }
    }
}
